import { reqUserLogin, reqUserInfo, reqLogOut } from "@/api";
import { setUserToken, removeUserToken } from "@/utils/token";
import { USER_INFO, CLEAR_TOKEN } from '@/store/mutation-types'

export default {
  namespaced: true,
  state: {
    userInfo: {}
  },
  actions: {
    //用户登录请求
    async userLogin(_, data) {
      try {
        const res = await reqUserLogin(data) //登录请求
        if (res.code == 200) {
          setUserToken(res.data.token) //本地存储登录成功的token
          return Promise.resolve('登录成功')
        }
        throw (res.message)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    //获取用户信息
    async getUserInfo({ commit }) {
      try {
        const res = await reqUserInfo()
        if (res.code == 200) {
          commit(USER_INFO, res.data)
          return Promise.resolve('获取成功')
        }
        throw (res.message)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    //退出登录
    async logOut({ commit }) {
      try {
        const res = await reqLogOut()
        if (res.code == 200) {
          commit(CLEAR_TOKEN)
          return Promise.resolve('退出登录成功')
        }
        throw (res.message)
      } catch (error) {
        return Promise.reject(error)
      }
    }
  },
  mutations: {
    [USER_INFO]: (context, data) => context.userInfo = data,
    [CLEAR_TOKEN]: (context) => {
      context.userInfo = ''
      removeUserToken()
    }
  },
  getters: {}
}